package com.blog.admin.service.impl;

import com.blog.admin.service.FileService;
import com.blog.common.utils.Assert;
import com.blog.common.utils.StringsUtils;
import com.blog.common.utils.UUIDUtils;
import com.blog.common.vo.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("adminFileService")
@PropertySource("classpath:/properties/filePath.properties")
public class FileServiceImpl implements FileService {

    @Value("${admin.dirPath}")
    private String dirPath;
    @Value("${admin.urlPath}")
    private String urlPath;
    @Override
    public JsonResult upload(MultipartFile uploadFile) {
        JsonResult res = null;
        Assert.valid(uploadFile,"上传文件为空！");
        String fileName = uploadFile.getOriginalFilename();
        if(StringsUtils.isNotBlank(fileName)){
            String suffix = "";
            if(fileName.lastIndexOf(".") !=-1 ){
                String name = fileName.substring(0,fileName.lastIndexOf("."));
                suffix = fileName.substring(fileName.lastIndexOf("."));
            }
            String localFileName = UUIDUtils.getUUID()+suffix;
            String basePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            try {
                File file = new File(dirPath + basePath + localFileName);
                if(!file.exists()){
                    file.mkdirs();
                }
                uploadFile.transferTo(file);
                String url = urlPath + basePath + localFileName;
                Map data = new HashMap();
                data.put("url", url);
                res = JsonResult.success(data);
            } catch (Exception e){
                e.printStackTrace();
                res = JsonResult.fail("保存文件失败");
            }
        } else{
            res = JsonResult.fail("文件名读取失败");
        }
        return res;
    }
}
